package com.wang.html2richtext.utils;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangzhiguo on 2019/6/16 0016.
 */
public class CorePaser {

	public static Document getDocument(String url) {
		String content = HttpClientUtil.get(url);
		Document document = Jsoup.parse(content);
		return document;
	}

	private String filePath;
	private String filePathStart;
	public CorePaser(String filePath,String filePathStart){
		this.filePath = filePath;
		this.filePathStart = filePathStart;
	}
	/**
	 * 判断element元素是否图片，如果是，则下载到本地
	 * @param element
	 */
	public void downloadImg(Element element){

        Tag tag = element.tag();
        String tagName = tag.getName();
        if (tagName.equals("img")) {
            img(element, filePath, filePathStart);
        }
        List<Element> children = element.children();
		if(!CollectionUtils.isEmpty(children)){
			children.forEach(e->{
				//穷举到所有根节点
                downloadImg(e);
			});
		}else{
			return;
		}

	}
	private static void img(Element element,String filePath, String filePathStart) {

		String url = element.attr("data-src");
		System.out.println("data-src:" + url);
		String fix = FileUtil.getPicture(url, filePath, filePathStart);
		// todo 这里的相对路径可配置为常量
//		String url_new = "../images/" + fix;
		element.attr("src", fix);

	}
}
